<?php

declare(strict_types=1);

namespace app\controller\trade;

use app\BaseController;
use app\service\factory\ResponseFactory;
use app\service\order\AfterSaleService;
use app\validate\order\RefundValidate;
use think\Response;
use Throwable;

class AfterSale extends BaseController
{
    public function index(AfterSaleService $afterSaleService): Response
    {
        try {
            $userId = (int) ($this->request->user_id ?? 0);
            if ($userId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;
            $view = (string) $this->request->param('view', 'buyer');
            $filters = [];

            switch ($view) {
                case 'seller':
                    $filters['seller_id'] = $userId;
                    break;
                case 'assistant':
                    $filters['assist_user_id'] = $userId;
                    break;
                case 'buyer':
                case '':
                    $filters['buyer_id'] = $userId;
                    break;
                default:
                    return json(ResponseFactory::error('视图参数不正确', 422));
            }

            $status = $this->request->param('status');
            if ($status !== null && $status !== '') {
                $filters['status'] = (int) $status;
            }

            $keyword = $this->request->param('keyword');
            if ($keyword !== null && $keyword !== '') {
                $filters['keyword'] = (string) $keyword;
            }

            $paginator = $afterSaleService->paginate($filters, $page, $pageSize);
            $list = array_map(static fn($item) => $item->toArray(), $paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, AfterSaleService $afterSaleService): Response
    {
        try {
            $userId = (int) ($this->request->user_id ?? 0);
            if ($userId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $refund = $afterSaleService->get($id, $userId);
            return json(ResponseFactory::success($refund->toArray()));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function save(AfterSaleService $afterSaleService): Response
    {
        try {
            $buyerId = (int) ($this->request->user_id ?? 0);
            if ($buyerId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $payload = $this->request->post();
            $this->validate($payload, RefundValidate::class . '.apply');

            $refund = $afterSaleService->apply($buyerId, $payload);

            return json(ResponseFactory::success($refund->toArray(), '退款申请已提交'));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function update(int $id, AfterSaleService $afterSaleService): Response
    {
        try {
            $userId = (int) ($this->request->user_id ?? 0);
            if ($userId <= 0) {
                return json(ResponseFactory::error('未登录或缺少用户信息', 401));
            }

            $payload = $this->request->put();
            $this->validate($payload, RefundValidate::class . '.update');

            $action = (string) ($payload['action'] ?? '');
            if ($action === '') {
                return json(ResponseFactory::error('缺少操作类型', 422));
            }

            switch ($action) {
                case 'approve':
                    $refund = $afterSaleService->approve($id, $userId, $payload);
                    $message = '退款已审批通过';
                    break;
                case 'reject':
                    $refund = $afterSaleService->reject($id, $userId, $payload);
                    $message = '退款已驳回';
                    break;
                case 'complete':
                    $refund = $afterSaleService->complete($id, $userId, $payload);
                    $message = '退款已完成';
                    break;
                default:
                    return json(ResponseFactory::error('不支持的操作', 422));
            }

            return json(ResponseFactory::success($refund->toArray(), $message));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }
}
